package com.jt.common.interceptor;

import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 如何理解框架？ 设计好的一个半成品？（类似简历模板）
 * 框架设计时会有一些对象的定义以及这些对象的执行流程，类似一个执行链。
 */
//拦截器接口
interface HandlerInterceptor{
    default void before(){};
    default void after(){};
}
//处理器接口
interface Handler{
    void processed();
}
//执行链
class ExecutionChain{
    private List<HandlerInterceptor> interceptors = new CopyOnWriteArrayList<>();
    private Handler handler;

    public ExecutionChain(List<HandlerInterceptor> interceptors, Handler handler) {
        this.interceptors.addAll(interceptors);
        this.handler = handler;
    }

    public void ececute(){//负责执行业务的方法
        for (int i = 0;i<interceptors.size();i++){
            interceptors.get(i).before();
        }
        handler.processed();

        for (int i = interceptors.size()-1;i>=0;i--){
            interceptors.get(i).after();
        }
    }
}
public class FrameworkTests {
    public static void main(String[] args) {
        //创建拦截器集合
        List<HandlerInterceptor> list = new CopyOnWriteArrayList<>();
        //创建拦截器
        HandlerInterceptor handlerInterceptor1=new HandlerInterceptor() {
            @Override
            public void before() {
                System.out.println("===123===");
            }

            @Override
            public void after() {
                System.out.println("===456===");
            }
        };
        HandlerInterceptor handlerInterceptor2=new HandlerInterceptor() {
            @Override
            public void before() {
                System.out.println("===789===");
            }

            @Override
            public void after() {
                System.out.println("蟹不肉");
            }
        };
        list.add(handlerInterceptor1);
        list.add(handlerInterceptor2);


        Handler handler=new Handler() {
            @Override
            public void processed() {
                for (int i = 0;i<1;i++){
                    System.out.println("i="+i);
                }
            }
        };
        //创建拦截链对象
        ExecutionChain chain = new ExecutionChain(list,handler);
        chain.ececute();

    }
}
